<?php
function getMessages($itemID,$type) {
	global $dbname, $db, $db_selected;
	
	if ($type == 'contact') {
		$where = "M.ContactID = '$itemID' AND M.FollowUpID = 0";
		$join = '';
	} elseif ($type == 'toUser') {
		$where  = "MS.StaffID = '".$_SESSION['userid']."' OR M.ToAll = 1";
		$join   = 'LEFT JOIN cdc_linkMessageStaff MS ON M.MessageID = MS.MessageID';
		$msCols = ',MS.MessageRead,MS.ReadDateTime';
	}
	
	$sqlNotes = "SELECT M.MessageID,M.Message,M.ContactID,M.FollowUpID,M.DateEntry,M.Userid
			$msCols 
			FROM cdc_Messages M
			$join
			WHERE
				$where
			ORDER BY
				M.DateEntry DESC
				LIMIT 10";
	$resultNotes    = mysql_db_query($dbname,$sqlNotes);
	$totalRows      = mysql_num_rows($resultNotes);	
	$unread = getUnreadMessages();
		
	if (mysql_num_rows($resultNotes)>0) {
		$stringJSON   = '({"Unread":"'.$unread.'","Notes":[';
		while ($value = mysql_fetch_assoc($resultNotes)) {		
			$staffArray = getStaffInfo($value['Userid']);
			
			$value['StaffFName'] = $staffArray['StaffFName'];
			$value['StaffLName'] = $staffArray['StaffLName'];
			$value['StaffEmail'] = $staffArray['StaffEmail'];
			$value['StaffPhone'] = $staffArray['StaffPhone'];
			$value['StaffRole']  = $staffArray['LevelSecurity'];
			
			$noteDate = new Zend_Date($value['DateEntry'], Zend_Date::ISO_8601, 'en_US');
			$newDate = $noteDate->toString('MMM d, h:m a');
			$value['DateEntry'] = $newDate;
			
			$noteReadDate = new Zend_Date($value['ReadDateTime'], Zend_Date::ISO_8601, 'en_US');
			$newReadDate = $noteReadDate->toString('MMM d, h:m a');
			$value['ReadDateTime'] = $newReadDate;			
			
			if (empty($value['MessageRead'])) {
				$value['MessageRead'] = '0';
				$value['ReadDateTime'] = '0';
			}
			
			$stringJSON .= Zend_Json::encode($value).','; 
		}
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';		
	} else {
		$stringJSON = 0;
	}	
	return $stringJSON;
}

function markMessageRead($messageID) {
	global $dbname, $db, $db_selected;
	
	$sql = "UPDATE cdc_linkMessageStaff 
			SET 
				MessageRead = 1,
				ReadDateTime = '".date('Y-m-d G:i:s')."'
			WHERE
				MessageID = '$messageID' AND
				StaffID = '".$_SESSION['userid']."'";
	$result = mysql_db_query($dbname,$sql);
	
	$unread = getUnreadMessages();
	return $unread;
}

function getUnreadMessages() {
	global $dbname, $db, $db_selected;
	
	/*
	 * Get number of unread messages
	 */
	$sqlUnread = "SELECT COUNT(MessageID) AS Unread from cdc_linkMessageStaff 
					WHERE 
						StaffID = '".$_SESSION['userid']."' AND
						MessageRead = 0";
	$resultUnread = mysql_db_query($dbname,$sqlUnread);
	$rowUnread = mysql_fetch_assoc($resultUnread);
	return $rowUnread['Unread'];
}

function saveMessage2($phpJSON) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = stripslashes($phpJSON);
	$phpArray = Zend_Json::decode($phpJSON);
	
	$staffID = $phpArray['staffID'];
	$message = fieldToDB($phpArray['message']);
	
	if ($staffID == 'All staff') {
		$toAll = 1;
	} else {
		$toAll = 0;
	}
	
	/*
	 * Log message to dbase
	 */
	$sql = "INSERT into cdc_Messages (
			Message,
			ToAll,
			DateEntry,
			DateUpdate,
			Userid
			) values (
			'$message',
			'$toAll',
			'".date('Y-m-d G:i:s')."',
			'".date('Y-m-d')."',
			'".$_SESSION['userid']."'	
			)";
	$result = mysql_db_query($dbname,$sql);
	$messageID = mysql_insert_id();
	
	/*
	 * Log staffTo Userid
	 */
	if ($staffID != 'All staff') {
		$sql = "INSERT into cdc_linkMessageStaff (
				MessageID,
				StaffID
				) values (
				'$messageID',
				'$staffID'
				)";
		$result = mysql_db_query($dbname,$sql);
		
		/*
		 * Send email to staff member
		 */
		sendMessageEmail($staffID,$message);
	}	
}

function saveMessage($phpJSON,$itemID,$type) {
	global $dbname, $db, $db_selected;
	
	if ($type == 'contact') {
		$itemField = 'ContactID';		
	}
	
	// Decode JSON
	$phpJSON = stripslashes($phpJSON);
	$phpArray = Zend_Json::decode($phpJSON);
	
	$notes  = fieldToDB($phpArray['notes']);
	
	if (!empty($notes)) {	
		$sqlNotes = "INSERT into cdc_Messages (
				Message,
				$itemField,
				DateEntry,
				DateUpdate,
				Userid
				) values (
				'$notes',
				'$itemID',
				'".date('Y-m-d G:i:s')."',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'	
				)";
		$resultNotes = mysql_db_query($dbname,$sqlNotes);
	}	
	
	/*
	 * Get any existing notes for this contactID
	 */
	$stringJSON = getMessages($itemID,$type);
	return $stringJSON;
}

// TODO: Create one master saveMessage function
?>